import sys
import traceback

from rest_framework.response import Response
from rest_framework.status import HTTP_200_OK

from utils.handlers.exception import exception_response
from utils.mixins.common_mixins.logger import error_logger


class SuccessResponse(Response):
    """
    格式化response, 并打印日志
    """

    def __init__(self, data=None, code=200, status=HTTP_200_OK, msg='success', **kwargs):
        _data = {
            'code': code,
            'data': data,
            'msg': msg,
            **kwargs
        }
        super().__init__(data=_data, status=status)


class PageResponse(Response):
    """
    分页响应
    """

    def __init__(self, data, msg='success', page=1, count=None):
        if count is None:
            count = len(data)
        _data = {
            'code': 200,
            'data': {
                'page': page,
                'count': count,
                'results': data
            },
            'msg': msg
        }
        super().__init__(data=_data, status=HTTP_200_OK)


class FailedResponse(Response):
    """
    格式化response, 并打印错误日志
    """

    def __init__(self, error, data=None):
        # Ynet异常类, 根据error_code与error返回
        msg, code, status = exception_response(error)

        _data = {
            'code': code,
            'data': data,
            'msg': msg,
        }
        super().__init__(data=_data, status=status)
        if any(sys.exc_info()):
            error_logger.error(traceback.format_exc())
